package myoa

import myoa.excel.ExcelSheetName
import org.apache.poi.hssf.util.CellReference
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Row
import org.grails.plugins.excelimport.AbstractExcelImporter
import org.grails.plugins.excelimport.ExcelImportService

class ExcelImpService extends AbstractExcelImporter {
    /**
     * default(singleton) is NOT thread safe, since extends workbook prototype from AbstractExcelImporter
     * request -- 同一浏览器的同一tab是线程安全的
     * session -- 不同（厂商）浏览器间是线程安全的，同一浏览器的不同tab是不安全的（但一般没人那么无聊吧，所以这就够了）
     */
    static scope = 'session'

    ExcelImportService excelImportService

    //import from excel file stored on server "file-store"
    List<Map> imp(Long excelFileStoreId, ExcelSheetName sheetName) {
        FileStore fs = FileStore.findById(excelFileStoreId)
        imp(fs, sheetName)
    }

    List<Map> imp(FileStore excelFileStore, ExcelSheetName sheetName) {
        String excelPath = excelFileStore.path
        assert new File(excelPath).exists()
        this.read(excelPath)

        Map config = getConfig(sheetName.name())
        excelImportService.columns(workbook, config)
    }

    /**
     * @param sheetName = domain instance name
     * @return 利用表单第一行自动生成Excel Config
     */
    private Map getConfig(String sheetName) {
        Map columnMap = [:]
        Row title = workbook.getSheet(sheetName).getRow(0)  //first row for title
        List<Cell> list = title.toList()
        list.each {
            String column = CellReference.convertNumToColString(it.columnIndex)
            columnMap.put(column, it.stringCellValue)
        }
        Map config = [sheet: sheetName, startRow: 1, columnMap: columnMap]
        return config
    }
}
